<template>
  <div class="lend_review_wrap">
    <!-- 查询表单卡片 -->
    <el-card class="lend_review_query_form_card">
      <div class="lend_review_form_box">
        <el-form :inline="true" :model="queryFormData" class="demo-form-inline">
          <el-form-item label="学生姓名">
            <template #label>
              <i class="iconfont icon-xingming" style="font-size: 19px"></i>
              <span>学生姓名</span>
            </template>
            <el-input style="width: 120px" v-model="queryFormData.studentName" placeholder="" clearable />
          </el-form-item>

          <el-form-item label="学生工号">
            <template #label>
              <i class="iconfont icon-gonghao" style="font-size: 19px"></i>
              <span>学生工号</span>
            </template>
            <el-input style="width: 180px" v-model="queryFormData.studentCode" placeholder="" clearable />
          </el-form-item>

          <!-- <el-form-item label="学生手机号">
            <el-input style="width: 180px" v-model="queryFormData.studentPhone" placeholder="" clearable />
          </el-form-item> -->

          <el-form-item label="借出设备">
            <template #label>
              <i class="iconfont icon-yiqihecha" style="font-size: 19px"></i>
              <span>预约仪器</span>
            </template>
            <el-input style="width: 220px" v-model="queryFormData.lendDev" placeholder="" clearable />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :icon="Search" @click="queryClick">查询</el-button>
            <!-- 操作按钮 -->
            <div class="action_box">
              <el-button v-if="!isAuditor" type="success" :icon="Promotion" @click="lendApplyClick">借出申请</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 表格卡片 -->
    <el-card class="lend_review_table_card">
      <div class="lend_review_table_box">
        <el-table :data="lendReviewList">
          <el-table-column prop="num" label="序号" width="60" align="center"></el-table-column>
          <el-table-column prop="studentCode" label="学生工号" align="center" width="120"></el-table-column>
          <el-table-column prop="studentName" label="学生姓名" align="center" width="80"></el-table-column>
          <el-table-column prop="studentPhone" label="学生手机号" align="center" width="120"></el-table-column>
          <el-table-column prop="lendDev" label="借出设备" align="center"></el-table-column>
          <el-table-column prop="lendCount" label="数量" align="center" width="80"></el-table-column>
          <el-table-column prop="teacherName" label="导师姓名" align="center" width="80"></el-table-column>
          <el-table-column prop="lendTime" label="借出时间" align="center" width="180"></el-table-column>
          <!-- <el-table-column prop="applyTime" label="申请时间" align="center" width="180"></el-table-column> -->
          <el-table-column prop="estimateReturnTime" label="预计归还时间" align="center" width="180"></el-table-column>

          <el-table-column prop="returnTime" label="归还时间" align="center" width="180"></el-table-column>
          <el-table-column prop="devLendDesc" label="申请备注" align="center" width="120"></el-table-column>

          <el-table-column prop="checkPeople" label="审核人" align="center" width="80"></el-table-column>
          <el-table-column prop="checkDesc" label="审核备注" align="center" width="120"></el-table-column>
          <el-table-column prop="returnTime" label="状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.status == 1" type="warning">待审核</el-tag>
              <el-tag v-if="scope.row.status == 2" type="primary">待归还</el-tag>
              <el-tag v-if="scope.row.status == 3" type="danger">不通过</el-tag>
              <el-tag v-if="scope.row.status == 0" type="success">已归还</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="action" label="操作" align="center" width="80" v-if="isAuditor">
            <template #default="scope">
              <!-- 审核按钮 -->
              <el-button
                v-if="isAuditor && scope.row.status == 1"
                size="small"
                color="#626aef"
                class="check_btn"
                plain
                @click="checkBtnClick(scope.row)"
              >
                <i class="iconfont icon-shenhe" style="margin-right: 4px; position: relative; top: -1px; font-size: 15px"></i>
                审核
              </el-button>

              <!-- 归还按钮 -->
              <el-popconfirm
                v-if="isAuditor && scope.row.status == 2"
                class="box-item"
                title="确认归还吗?"
                placement="top-start"
                @confirm="returnConfirmClick(scope.row)"
              >
                <template #reference
                  ><el-button size="small" type="primary" class="return_btn" plain>
                    <i class="iconfont icon-guihuan" style="margin-right: 4px"></i> 归还
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination_box">
          <el-pagination
            class="table_pagination"
            background
            layout="prev, pager, next"
            v-model:current-page="queryFormData.page"
            :page-size="queryFormData.size"
            :total="total"
            @change="tablePaginationChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 借出申请弹窗 -->
    <el-dialog class="lend_apply_dialog" title="发起借出申请" v-model="isShowLendApply" width="540">
      <div class="lend_apply_box">
        <el-form :model="launchLendFormData" :rules="launchLendFormRules" label-width="auto" ref="launchLendFormRef">
          <el-form-item label="学生工号" prop="studentCode">
            <el-input v-model="launchLendFormData.studentCode" style="width: 220px" placeholder="请输入学生工号" />
          </el-form-item>
          <el-form-item label="学生姓名" prop="studentName">
            <el-input v-model="launchLendFormData.studentName" style="width: 220px" placeholder="请输入学生姓名" />
          </el-form-item>
          <el-form-item label="学生手机号" prop="studentPhone">
            <el-input v-model="launchLendFormData.studentPhone" style="width: 220px" placeholder="请输入学生手机号" />
          </el-form-item>
          <el-form-item label="借出设备" prop="lendDevName">
            <el-input v-model="launchLendFormData.lendDevName" style="width: 220px" placeholder="请输入设备名称" />
          </el-form-item>
          <el-form-item label="借出数量" prop="lendDevCount">
            <el-input-number
              v-model="launchLendFormData.lendDevCount"
              :min="1"
              :max="100000"
              type="number"
              style="width: 150px"
              placeholder="请输入设备数量"
            />
          </el-form-item>
          <el-form-item label="借出时间" prop="lendTime">
            <el-date-picker
              v-model="launchLendFormData.lendTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetime"
              placeholder="请选择借出时间"
            />
          </el-form-item>
          <el-form-item label="预计归还时间" prop="returnTime">
            <el-date-picker
              v-model="launchLendFormData.returnTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetime"
              placeholder="请选择归还时间"
            />
          </el-form-item>
          <el-form-item label="导师姓名" prop="mentorName">
            <el-input v-model="launchLendFormData.mentorName" style="width: 220px" placeholder="请输入导师姓名" />
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              v-model="launchLendFormData.devLendDesc"
              :autosize="{ minRows: 4, maxRows: 6 }"
              type="textarea"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="lendDialogCancelClick">取消</el-button>
          <el-button type="primary" @click="lendDialogOkClick"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog
      class="lend_apply_dialog"
      :title="`审核-${currentCheckLendInfo.studentName}发起的借出申请`"
      v-model="isShowCheckDialog"
      width="540"
    >
      <div class="lend_apply_box">
        <el-form :model="checkFormData" :rules="checkFormRules" ref="checkFormRef" label-width="auto">
          <el-form-item label="审核结果" prop="checkStatus" style="margin-top: 30px">
            <el-check-tag
              class="pass_tag"
              :checked="checkFormData.checkStatus == 2"
              type="success"
              @change="tagPassChange"
              :disable-transitions="true"
            >
              <i class="iconfont icon-pass-2-copy"></i>
              通过
            </el-check-tag>
            <el-check-tag
              class="not_pass_tag"
              :checked="checkFormData.checkStatus == 3"
              type="danger"
              @change="tagNotPassChange"
              :disable-transitions="true"
            >
              <i class="iconfont icon-butongguo"></i>
              不通过
            </el-check-tag>
          </el-form-item>

          <el-form-item label="审核备注" style="margin-top: 30px">
            <el-input
              v-model="checkFormData.checkDesc"
              :autosize="{ minRows: 4, maxRows: 6 }"
              type="textarea"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="checkDialogCancelClick">取消</el-button>
          <el-button type="primary" @click="checkDialogOkClick"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from "vue";
import "./index.scss";
import { ElMessage } from "element-plus";
export default defineComponent({
  name: "LendReview"
});
</script>
<script lang="ts" setup>
import { Search, Promotion } from "@element-plus/icons-vue";
import { selectDevLendByPageApi, devLendApplyApi, devLendCheckApi, devLendReturnApi } from "@/api/modules/lendReview/index";
//

// 归还确定点击事件
const returnConfirmClick = async row => {
  let data = {
    devLendId: row.devLendId
  };
  await devLendReturnApi(data)
    .then(res => {
      if (res.result == "success") {
        ElMessage.success("归还成功");
      } else if (res.result == "error") {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {
      ElMessage.error("归还失败");
    })
    .finally(() => {
      selectLendReviewListByPageFunc();
    });
};

// 审核表单校验规则
const checkFormRules = ref({
  checkStatus: [{ required: true, message: "请选择审核结果", trigger: "blur" }]
});

// 审核表单Ref
const checkFormRef = ref(null);

// 审核表单数据
const checkFormData = ref({
  devLendId: null,
  checkStatus: null,
  checkDesc: ""
});

//审核通过tag change事件
const tagPassChange = e => {
  if (e) {
    checkFormData.value.checkStatus = 2;
  } else {
    checkFormData.value.checkStatus = null;
  }
};

// 审核不通过tag change事件
const tagNotPassChange = e => {
  if (e) {
    checkFormData.value.checkStatus = 3;
  } else {
    checkFormData.value.checkStatus = null;
  }
};

// 重置审核表单
const checkFormReset = () => {
  checkFormData.value = {
    devLendId: null,
    checkStatus: null,
    checkDesc: ""
  };
  checkFormRef.value.resetFields();
};

// 审核弹窗取消点击事件
const checkDialogCancelClick = () => {
  isShowCheckDialog.value = false;
  checkFormReset();
};

// 审核确定点击事件
const checkDialogOkClick = () => {
  checkFormRef.value.validate((valid, fields) => {
    console.log(checkFormData.value);
    if (valid) {
      console.log("submit!");
      checkRequest();
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 审核请求函数
const checkRequest = async () => {
  let data = {
    devLendId: checkFormData.value.devLendId,
    status: checkFormData.value.checkStatus,
    checkDesc: checkFormData.value.checkDesc
  };
  console.log("#审核请求数据", data);
  await devLendCheckApi(data)
    .then(res => {
      if (res.result == "success") {
        isShowCheckDialog.value = false;
        checkFormReset();
        ElMessage.success("提交成功");
      } else if (res.result == "error") {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {
      ElMessage.error("提交失败");
    })
    .finally(() => {
      selectLendReviewListByPageFunc();
    });
};

// 当前审核的借出申请信息
const currentCheckLendInfo = ref({});

// 是否是审核人
const isAuditor = ref(false);

// 显示借出申请弹窗的标识
const isShowLendApply = ref(false);

// 显示审核弹窗的标识
const isShowCheckDialog = ref(false);

// 审核表单数据
// const checkFormData = ref({
//   checkResult: null,
//   checkDesc: ""
// });

// // 审核表单校验规则
// const checkFormRules = ref({});

// 查询表单数据
const queryFormData = ref({
  page: 1,
  size: 10,
  studentCode: "",
  studentName: "",
  lendDev: ""
});

// 发起借出表单数据
const launchLendFormData = ref({
  // 学生工号
  studentCode: "",
  // 学生姓名
  studentName: "",
  // 学生手机号
  studentPhone: "",
  // 借出时间
  lendTime: "",
  // 归还时间
  returnTime: "",
  // 借出设备
  lendDevName: "",
  // 借出设备数量
  lendDevCount: 0,
  // 导师姓名
  mentorName: ""
});

// 发起借出表单Ref
const launchLendFormRef = ref(null);

// 发起借出表单校验规则
const launchLendFormRules = ref({
  studentCode: [{ required: true, message: "请输入学生工号", trigger: "blur" }],
  studentName: [{ required: true, message: "请输入学生姓名", trigger: "blur" }],
  studentPhone: [{ required: true, message: "请输入学生手机号", trigger: "blur" }],
  lendTime: [{ required: true, message: "请选择借出时间", trigger: "blur" }],
  returnTime: [{ required: true, message: "请选择归还时间", trigger: "blur" }],
  lendDevName: [{ required: true, message: "请输入借出设备", trigger: "blur" }],
  lendDevCount: [{ required: true, message: "请输入借出数量", trigger: "blur" }],
  mentorName: [{ required: true, message: "请输入导师姓名", trigger: "blur" }]
});

/*
  状态
  0   待审核
  1   审核通过-待归还
  2   审核不通过
  3   已归还
*/

// 列表总数
const total = ref(100);

// 借出审核列表
const lendReviewList = ref([]);

// 借出弹窗确定点击事件
const lendDialogOkClick = async () => {
  // 校验表单
  if (!launchLendFormRef.value) return;
  await launchLendFormRef.value.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      lendRequest();
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 借出请求函数
const lendRequest = async () => {
  let data = {
    studentCode: launchLendFormData.value.studentCode,
    studentName: launchLendFormData.value.studentName,
    studentPhone: launchLendFormData.value.studentPhone,
    lendTime: launchLendFormData.value.lendTime,
    estimateReturnTime: launchLendFormData.value.returnTime,
    lendDev: launchLendFormData.value.lendDevName,
    lendCount: launchLendFormData.value.lendDevCount,
    teacherName: launchLendFormData.value.mentorName,
    devLendDesc: launchLendFormData.value.devLendDesc
  };

  await devLendApplyApi(data)
    .then(res => {
      if (res.result == "success") {
        ElMessage.success("发起申请成功");
        launchLendFormRef.value.resetFields();
        resetLendFormData();
        isShowLendApply.value = false;
      } else if (res.result == "error") {
        ElMessage.error(res.msg);
      }
    })
    .finally(() => {
      selectLendReviewListByPageFunc();
    });
};

// 借出弹窗取消点击事件
const lendDialogCancelClick = () => {
  isShowLendApply.value = false;
  launchLendFormRef.value.resetFields();
  resetLendFormData();
};

// 重置发起借出申请表单数据
const resetLendFormData = () => {
  launchLendFormData.value = {
    // 学生工号
    studentCode: "",
    // 学生姓名
    studentName: "",
    // 学生手机号
    studentPhone: "",
    // 借出时间
    lendTime: "",
    // 归还时间
    returnTime: "",
    // 借出设备
    lendDevName: "",
    // 借出设备数量
    lendDevCount: 0,
    // 导师姓名
    mentorName: ""
  };
};

// 审核点击事件
const checkBtnClick = e => {
  console.log(e);
  checkFormData.value.devLendId = e.devLendId;
  currentCheckLendInfo.value = e;
  isShowCheckDialog.value = true;
};

// 借出申请点击事件
const lendApplyClick = () => {
  isShowLendApply.value = true;
};

// 表格分页器change事件
const tablePaginationChange = e => {
  queryFormData.value.page = e;
  selectLendReviewListByPageFunc();
};

// 查询点击事件
const queryClick = () => {
  selectLendReviewListByPageFunc();
};

// 处理字段空
const fieldNullDispose = val => {
  let str;
  if (val == null || val == undefined || val == "") {
    str = "--";
  } else {
    str = val;
  }
  return str;
};

// 分页查询借出审核列表
const selectLendReviewListByPageFunc = async () => {
  let data = queryFormData.value;

  await selectDevLendByPageApi(data).then(res => {
    console.log(res);
    res.data.list.forEach(item => {
      item.returnTime = fieldNullDispose(item.returnTime);
      item.checkDesc = fieldNullDispose(item.checkDesc);
      item.devLendDesc = fieldNullDispose(item.devLendDesc);
    });
    lendReviewList.value = res.data.list;
    total.value = res.data.total;
  });

  // console.log(data);
  // console.log(lendReviewList.value);

  tableNumComp();
};

// 表格序号计算
const tableNumComp = () => {
  let page = queryFormData.value.page;
  let size = queryFormData.value.size;
  lendReviewList.value.forEach((item, index) => {
    item.num = (page - 1) * size + (index + 1);
  });

  console.log(lendReviewList.value);
};

// init
onMounted(() => {
  selectLendReviewListByPageFunc();

  // console.log("#身份", localStorage.getItem("permission"));

  isAuditor.value = JSON.parse(localStorage.getItem("permission")).isManager == 1 ? true : false;
  console.log("#身份", isAuditor.value);
});
</script>

<style lang="scss" scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.demo-datetime-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}
.demo-datetime-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.demo-datetime-picker .block:last-child {
  border-right: none;
}
.demo-datetime-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>
